package structure;

import java.util.Arrays;

public class MyArrayList2<E> {
    // 1. 构造数组
    private static final int DEFAULT_CAPACITY = 10;
    private Object[] elem;
    private int size;

    public MyArrayList2() {
        this.elem = new Object[DEFAULT_CAPACITY];
    }

    // 2. 判断数组是否为空为满
    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == elem.length;
    }

    private void grow() {
        this.elem = Arrays.copyOf(elem, elem.length * 2);
    }

    // 3.插入元素
    public void add(int val) {
        if (isFull()) {
            grow();
        }
        elem[size++] = val;
    }

    public int size() {
        return size;
    }

    // 4.在指定位置插入元素
    public void addIndex(E val, int index) {
        if (index < 0 || index > size) {
            return;
        }
        if (isFull()) {
            grow();
        }

        int i = size - 1;
        while (i >= index){
            elem[i+1] = elem[i];
            i--;
        }
        elem[index] = val;
        size++;
    }

    // 5.查找某个元素, 返回其下标
    public int indexOf(E val) {
        for (int i = 0; i < size; i++) {
            if (elem[i] == val) {
                return i;
            }
        }
        return -1;
    }

    // 6.判断是否存在某个元素
    public boolean contains(E val) {
        return indexOf(val) != -1;
    }

    // 7.通过下标查找元素并返回
    public E get(int index) {
        if (index < 0 || index >= size) {
            return null;
        }
        return (E) elem[index];
    }

    // 8.删除某个元素
    public boolean remove(E val) {
        if (isEmpty()) {
            return false;
        }
        int index = indexOf(val);
        if (index != -1) {
            for (int j = index; j < size - 1; j++) {
                elem[j] = elem[j + 1];
            }
            size--;
            return true;
        }
        return false;
    }

    // 9.删除为key的所有元素
    public boolean removeAll(E val) {
        if (isEmpty()) {
            return false;
        }
        int index = indexOf(val);
        boolean modified = false;
        while (index != -1) {
            for (int i = index; i < size - 1; i++) {
                elem[i] = elem[i + 1];
            }
            size--;
            modified = true;
            index = indexOf(val);
        }
        return modified;
    }

    // 10.更新数据
    public void set(int index, E val) {
        if (index < 0 || index >= size) {
            return;
        }
        elem[index] = val;
    }

    // 11.打印数据
    public void print() {
        for (int i = 0; i < size; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }

    // 13.清空顺序表
    public void clear() {
        size = 0;
    }
}
